#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"
#include "Comm.hpp"
using namespace std;
using namespace ThreadModule;

void Usage(string pro)
{
    cout << "Usage:\t\n"
         << pro << " serverip serverport\n"
         << endl;
}

int InitClient(string &serverip, uint16_t serverport, struct sockaddr_in *server)
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket error" << endl;
        return -1;
    }

    memset(server, 0, sizeof(struct sockaddr_in));
    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());

    return sockfd;
}

void recvmessage(int sockfd, string name)
{
    while (true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;                                     // 接收信息到buffer，然后在buffer末尾加\0
            fprintf(stderr, "[%s]%s\n", name.c_str(), buffer); // 将接收到的数据和给定的名称一起输出到标准错误流
        }
    }
}

void sendmessage(int sockfd, struct sockaddr_in &server, string name)
{
    string message;
    while (true)
    {
        printf("%s | Enter# ", name.c_str());
        fflush(stdout);
        getline(cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct sockaddr_in serveraddr;
    int sockfd=InitClient(serverip,serverport,&serveraddr);
    if(sockfd==-1)
    {
        return 1;
    }

    func_t r=bind(&recvmessage,sockfd,placeholders::_1);
    func_t s=bind(&sendmessage,sockfd,serveraddr,placeholders::_1);

    Thread Recver(r,"recver");
    Thread Sender(s,"sender");

    Recver.Start();
    Sender.Start();

    Recver.Join();
    Sender.Join();

    return 0;
}